<template>
  <view class="xl-address-form">
    <xl-navbar :title="title" :back="routerBack" leftIcon="xl-left" @click-left="clickNavbarLeft"></xl-navbar>
    <view class="address-form">
      <view class="form-box recognition-box">
        <view class="textarea-box">
					<textarea
              class="textarea"
              v-model="recognitionText"
              rows="4"
              placeholder="「粘贴识别」或输入文本，智能拆分姓名、电话和地址"
              placeholder-style="line-height: 1.5;font-size: 30rpx;"
          ></textarea>
        </view>
        <view class="opt-box">
          <view class="copy" @click="handleCopy">
            <xl-icon name="xl-copy" color="#666666" right="2" top="1"></xl-icon>
            <text>粘贴</text>
          </view>
          <xl-button
              width="160rpx"
              height="56rpx"
              text="智能识别"
              :color="color"
              :textColor="btnTextColor"
              :fontSize="14"
              shape="circle"
              @click="handleRecognize"
          ></xl-button>
        </view>
      </view>
      <view class="form-box info-box">
        <view class="title-box">联系人信息</view>
        <view class="form-item">
          <view class="label">联系人</view>
          <view class="value">
            <input
                class="input"
                v-model="address[propNameConfig.name]"
                type="text"
                placeholder="请填写联系人姓名"
            />
          </view>
          <!-- #ifdef APP-PLUS || MP-WEIXIN -->
          <view v-if="showContact" class="more" @click="chooseContact">
            <xl-icon name="xl-contact" color="#888" size="28rpx" right="4"></xl-icon>
            <text>通讯录</text>
          </view>
          <!-- #endif -->
        </view>
        <view class="form-item">
          <view class="label">电话号码</view>
          <view class="value">
            <input
                class="input"
                v-model="address[propNameConfig.tel]"
                type="number"
                placeholder="请填写联系人姓名"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="label">所在地区</view>
          <view class="value">
            <xl-picker
                :defaultValue="defaultRegionValue"
                :options="regionData"
                valueName="name"
                :showChoose="true"
                :showLastLabel="false"
                placeholder="请选择所在地区"
                choosefontSize="32rpx"
                choosePadding="0"
                @change="changeRegion"
            ></xl-picker>
          </view>
          <view v-if="showLocation" class="more" @click="chooseLocation">
            <xl-icon name="xl-dizhi" size="30rpx" color="#888" right="4"></xl-icon>
            <text>定位</text>
          </view>
        </view>
        <view class="form-item">
          <view class="label">详细地址</view>
          <view class="value">
						<textarea
                class="textarea"
                v-model="address[propNameConfig.address]"
                placeholder="请填写详细地址(例如**街**号**)"
                placeholder-style="font-size: 32rpx; color: #808080;"
                auto-height
                rows="1"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="label">默认地址</view>
          <view class="value switch">
            <xl-switch
                v-model="address[propNameConfig.isDefault]"
                :activeColor="color"
                inactiveColor="rgb(230, 230, 230)"
                :space="2"
                :size="20"
            ></xl-switch>
          </view>
        </view>
      </view>
    </view>
    <view class="xl-address-form-footer">
      <xl-button
          width="640rpx"
          height="80rpx"
          :text="btnText"
          :color="color"
          :textColor="btnTextColor"
          shape="circle"
          @click="submit"
      ></xl-button>
    </view>

    <xl-back @back="clickNavbarLeft"></xl-back>
  </view>
</template>

<script setup>
import regionData from '../../libs/utils/citys.js'
import { parseAddress, parseAddressRegion } from '../../libs/utils/addressParse.js'
import { ref, computed, watch } from 'vue'
import propsData from './props'

const props = defineProps(propsData)
const emits = defineEmits(['submit', 'load', 'close'])

// 属性名称配置
const propNameConfig =  {
  id: props.propNames?.id || 'id',
  name: props.propNames?.name || 'name',
  tel: props.propNames?.tel || 'tel',
  province: props.propNames?.province || 'province',
  city: props.propNames?.city || 'city',
  district: props.propNames?.district || 'district',
  address: props.propNames?.address || 'address',
  isDefault: props.propNames?.isDefault || 'isDefault',
  lng: props.propNames?.lng || 'lng',
  lat: props.propNames?.lat || 'lat'
}
// 点击导航栏左边按钮触发
function clickNavbarLeft() {
  if(!props.routerBack) {
    emits('close')
  }
}
// 默认地区
const defaultRegionValue = ref([])
// 标题
const title = computed(() => props.addressId || props.data ? props.editTitle || '修改地址' : props.addTitle || '新增地址')
// 表单数据
const address = ref({})
// 监听传入的表单数据
watch(() => props.data, newVal => {
  if(newVal) {
    updateData(newVal)
  } else {
    reset()
  }
}, { immediate: true })

// 监听地址ID变化
watch(() => props.addressId, newVal => {
  // 未传入data数据，并且有地址ID 触发加载
  if(!props.data && newVal) {
    if(props.addressApi) {
      uni.$xl.apis[props.addressApi]({
        jointUrl: '/' + newVal
      }).then(res => {
        updateData(res.data)
      }).catch(err => {
        uni.$xl.toast(err)
      })
    } else {
      emits('load', props.addressId, updateData)
    }
  } else {
    reset()
  }
}, { immediate: true })
// 设置表单数据
function updateData(data) {
  reset()
  if(!data) return
  if(data[propNameConfig.province] && data[propNameConfig.city] && data[propNameConfig.district]) {
    defaultRegionValue.value = [data[propNameConfig.province], data[propNameConfig.city], data[propNameConfig.district]]
  } else {
    defaultRegionValue.value = []
  }
  address.value = data
}
// 提交表单
function submit() {
  emits('submit', { ...address.value })
}
// 重置表单数据
function reset() {
  let obj = {}
  for(let key in propNameConfig) {
    obj[propNameConfig[key]] = ''
  }
  address.value = obj
  defaultRegionValue.value = []
}
// 复制
function handleCopy() {
  uni.getClipboardData({
    success: function (res) {
      recognitionText.value = res.data
    },
    fail: function (err) {
      console.error('读取剪贴板失败:', err);
    }
  })
}
/**
 * 智能识别
 */
const recognitionText = ref('')
function handleRecognize() {
  let result = parseAddress(recognitionText.value)
  address.value[propNameConfig.name] = result.name
  address.value[propNameConfig.tel] = result.tel
  address.value[propNameConfig.province] =result.province
  address.value[propNameConfig.city] =result.city
  address.value[propNameConfig.district] =result.district
  address.value[propNameConfig.address] = result.detailAddress
  defaultRegionValue.value = [result.province, result.city, result.district]
}
// 选择联系人
function chooseContact() {
  uni.$xl.chooseContact().then(result => {
    address.value[propNameConfig.name] = result.name
    address.value[propNameConfig.tel] = result.tel
  }).catch(err => {
    console.log("获取联系人失败", err);
  })
}
// 切换地区
function changeRegion(e) {
  address.value[propNameConfig.province] = e[0]
  address.value[propNameConfig.city] = e[1]
  address.value[propNameConfig.district] = e[2]
}
// 定位
function chooseLocation() {
  uni.chooseLocation({
    success(result) {
      address.value[propNameConfig.lat] = result.latitude
      address.value[propNameConfig.lng] = result.longitude
      // markers.value = [{ id: uni.$xl.guid(), latitude: form.value.lat, longitude: form.value.lng }]
      let { province, city, district, detailAddress } = parseAddressRegion(result.address)
      address.value[propNameConfig.address] = detailAddress
      address.value[propNameConfig.province] = province
      address.value[propNameConfig.city] = city
      address.value[propNameConfig.district] = district
      defaultRegionValue.value = [province, city, district]
    },
    fail(err) {
      console.log('选择地址失败' + JSON.stringify(err));
    }
  })
}
</script>

<style lang="scss" scoped>
.xl-address-form {
  width: 750rpx;
}
.form-box {
  box-shadow: 0rpx 2rpx 10rpx rgba(0, 0, 0, 0.1);
  width: 690rpx;
  margin: 20rpx auto;
  padding: 30rpx;
  box-sizing: border-box;
  border-radius: 12rpx;
}
.recognition-box {
  .textarea-box {
    width: 100%;
    height: 160rpx;
    .textarea {
      width: 100%;
      height: 100%;
      font-size: 28rpx;
      line-height: 1.5;
    }
  }
  .opt-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .copy {
      color: #666666;
      font-size: 28rpx;
    }
    .read {

    }
  }
}
.info-box {
  margin-top: 40rpx;
  padding-bottom: 10rpx;
  .title-box {
    font-weight: 700;
    font-size: 32rpx;
    height: 60rpx;
    line-height: 60rpx;
    padding-bottom: 12rpx;
  }
  .form-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f1f1f1;
    padding: 36rpx 0;
    &:last-child {
      border: none;
    }
    .label {
      width: 160rpx;
      font-size: 32rpx;
      color: #000;
    }
    .value {
      flex: 1;
      margin: 0;
      .input {
        color: #333;
        font-size: 32rpx;
      }
      .textarea {
        font-size: 32rpx;
        width: 470rpx;
      }
      &.switch {
        display: flex;
        justify-content: flex-end;
      }
    }
    .more {
      display: flex;
      align-items: flex-start;
      color: #888;
      margin-left: 16rpx;
      font-size: 28rpx;
    }
  }
}
.xl-address-form-footer {
  background-color: #fff;
  box-sizing: border-box;
  position: fixed;
  z-index: 998;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 130rpx;
  width: 750rpx;
  box-shadow: 0px 2rpx 6rpx 0px rgba(0,0,0,0.2) ;
  gap: 30rpx;
}
</style>